//
//  WB_HttpManager.m
//  GhStaff
//
//  Created by mini3 on 2017/12/7.
//  Copyright © 2017年 GhStaff. All rights reserved.
//

#import "WB_HttpManager.h"
#import "AFURLRequestSerialization.h"

@interface WB_HttpManager()<NSURLConnectionDataDelegate>

@end

@implementation WB_HttpManager

///Post请求网络
- (void)requestPostWithUrl:(NSString *)url dictionaryParam:(NSDictionary *)param retquestId:(NSString *)requestId withResultBlock:(WBHttpPostRequestResultBlock)resultBlock
{
    NSURL *URL = [NSURL URLWithString:url];
    NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:[NSURL URLWithString:url]];
    [request setHTTPMethod:@"POST"];
    //Accept
    [request setValue:@"application/json" forHTTPHeaderField:@"Accept"];
    //Content-Type
    [request setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
    //Body
    [request setHTTPBody:[self returnDataWithDic:param]];

    request.timeoutInterval = 30;
    
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    [manager POST:URL.absoluteString parameters:param progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        [self requestSuccessForResponseObject:responseObject andRequestId:requestId withResultBlock:resultBlock];
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        [self againRequestUrl:url dictionaryParam:param requestCount:0 retquestId:requestId withResultBlock:resultBlock];
    }];
//    [op setCompletionBlockWithSuccess:^(AFHTTPRequestOperation * _Nonnull operation, id  _Nonnull responseObject) {
//
//    } failure:^(AFHTTPRequestOperation * _Nonnull operation, NSError * _Nonnull error) {
//
//
//    }];
//
//    [op start];
    
    
}


/// 请求网络 登录 注册  POST
- (void)requestPostLoginRegWithUrl:(NSString*)url
                   dictionaryParam:(NSDictionary*)param
                        retquestId:(NSString*)requestId
                   withResultBlock:(WBHttpPostRequestResultBlock)resultBlock
{
    NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:[NSURL URLWithString:url]];
    [request setHTTPMethod:@"POST"];
    //Accept
    [request setValue:@"application/json" forHTTPHeaderField:@"Accept"];
    //Content-Type
    [request setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
    //Body
    [request setHTTPBody:[self returnDataWithDic:param]];
    request.timeoutInterval = 30;
    
//    AFHTTPRequestOperation *op = [[AFHTTPRequestOperation alloc] initWithRequest:request];
//    [op setCompletionBlockWithSuccess:^(AFHTTPRequestOperation * _Nonnull operation, id  _Nonnull responseObject) {
//        [self requestSuccessForResponseObject:responseObject andRequestId:requestId withResultBlock:resultBlock];
//    } failure:^(AFHTTPRequestOperation * _Nonnull operation, NSError * _Nonnull error) {
//        [self requestFailureForError:error andRequestId:requestId withResultBlock:resultBlock];
//    }];
    
//    [op start];
}

/// 重置手机登录密码 PATCH
- (void)requestPatchResetPwdWithUrl:(NSString*)url
                    dictionaryParam:(NSDictionary*)param
                         retquestId:(NSString*)requestId
                    withResultBlock:(WBHttpPatchRequestResultBlock)resultBlock
{
    NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:[NSURL URLWithString:url]];
    [request setHTTPMethod:@"PATCH"];
    //Accept
    [request setValue:@"application/json" forHTTPHeaderField:@"Accept"];
    //Content-Type
    [request setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
    //Body
    [request setHTTPBody:[self returnDataWithDic:param]];
    request.timeoutInterval = 30;
    
//    AFHTTPRequestOperation *op = [[AFHTTPRequestOperation alloc] initWithRequest:request];
//    [op setCompletionBlockWithSuccess:^(AFHTTPRequestOperation * _Nonnull operation, id  _Nonnull responseObject) {
//        [self requestSuccessForResponseObject:responseObject andRequestId:requestId withResultBlock:resultBlock];
//    } failure:^(AFHTTPRequestOperation * _Nonnull operation, NSError * _Nonnull error) {
////        [self againRequestUrl:url dictionaryParam:param requestCount:0 retquestId:requestId withResultBlock:resultBlock];
//        [self requestFailureForError:error andRequestId:requestId withResultBlock:resultBlock];
//    }];
//
//    [op start];
}

/// 请求网络 GET
-(void)requestGetWithUrl:(NSString*)url
         dictionaryParam:(NSDictionary*)param
              retquestId:(NSString*)requestId
         withResultBlock:(WBHttpGetRequestResultBlock)resultBlock
{   
    NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:[NSURL URLWithString:url]];
    
    [request setHTTPMethod:@"GET"];
    //Accept
    [request setValue:@"application/json" forHTTPHeaderField:@"Accept"];
    //Content-Type
    [request setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
    [request setHTTPBody:[self returnDataWithDic:param]];
    //Token
//    [request setValue:DATAMODEL.token forHTTPHeaderField:@"token"];
    request.timeoutInterval = 30;
    
//    AFHTTPRequestOperation *op = [[AFHTTPRequestOperation alloc] initWithRequest:request];
//    [op setCompletionBlockWithSuccess:^(AFHTTPRequestOperation * _Nonnull operation, id  _Nonnull responseObject) {
//        [self requestSuccessForResponseObject:responseObject andRequestId:requestId withResultBlock:resultBlock];
//    } failure:^(AFHTTPRequestOperation * _Nonnull operation, NSError * _Nonnull error) {
////        [self againRequestUrl:url dictionaryParam:param requestCount:0 retquestId:requestId withResultBlock:resultBlock];
//        [self requestFailureForError:error andRequestId:requestId withResultBlock:resultBlock];
//    }];
//
//    [op start];
}




#pragma mark -- private
///dic转nsdata
- (NSData *)returnDataWithDic:(NSDictionary *)dic
{
    if(dic){
        NSData *data = [NSJSONSerialization dataWithJSONObject:dic options:NSJSONWritingPrettyPrinted error:nil];
        return data;
    }
    return nil;
}


/// 重新请求网络(网络请求错误重复请求)
-(void)againRequestUrl:(NSString*)url
       dictionaryParam:(NSDictionary*)param
          requestCount:(NSInteger)count
            retquestId:(NSString*)requestId
       withResultBlock:(WBHttpPostRequestResultBlock)resultBlock
{
    
    NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:[NSURL URLWithString:url]];
    [request setHTTPMethod:@"POST"];
    //Accept
    [request setValue:@"application/json" forHTTPHeaderField:@"Accept"];
    //Content-Type
    [request setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
    //token
//    [request setValue:[DATAMODEL.configDBHelper getToken] forHTTPHeaderField:@"token"];
    //Body
    [request setHTTPBody:[self returnDataWithDic:param]];
    request.timeoutInterval = 30;
    
//    AFHTTPSessionManager *op = [[AFHTTPRequestOperation alloc] initWithRequest:request];
//    [op setCompletionBlockWithSuccess:^(AFHTTPRequestOperation * _Nonnull operation, id  _Nonnull responseObject) {
//        [self requestSuccessForResponseObject:responseObject andRequestId:requestId withResultBlock:resultBlock];
//    } failure:^(AFHTTPRequestOperation * _Nonnull operation, NSError * _Nonnull error) {
//        if(count > 2){
//            [self requestFailureForError:error andRequestId:requestId withResultBlock:resultBlock];
//        }else{
//            [self againRequestUrl:url dictionaryParam:param requestCount:count + 1 retquestId:requestId withResultBlock:resultBlock];
//        }
//    }];
//    [op start];
}



/*
 *  JSON解析返回数据
 *
 *  @param  data  解析数据
 *
 *  @return 返回json解析数据
 */
- (id)JSONObjectWithData:(NSData *)data {
    
    if([data isKindOfClass:[NSDictionary class]]){
        return data;
    }
    
    // 如果没有数据返回，则直接不解析
    if (data.length == 0) {
        
        return nil;
    }
    // 初始化解析错误
    NSError *error = nil;
    
    // JSON解析
    id object = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableLeaves error:&error];
    
    return object;
}


///请求成功
-(void)requestSuccessForResponseObject:(id  _Nonnull)responseObject andRequestId:(NSString*)requestId withResultBlock:(WBHttpPostRequestResultBlock)resultBlock
{
    if (responseObject) {
        
        NSData * resultData = (NSData*)responseObject;
        //        NSString* resStr = [[NSString alloc]initWithData:resData encoding:NSUTF8StringEncoding];
        //        //解密
        //        NSString* decryptResStr = [Hen_AESEncryptorUtil AES128Decrypt:resStr key:AES_KEY];
        //        NSData* resultData =[decryptResStr dataUsingEncoding:NSUTF8StringEncoding];
        
        NSString *errCode = @"1";
        NSString *errMsg = @"未知错误";
        id data = nil;
        if (responseObject) {
            id objc = [self JSONObjectWithData:resultData];
            
            if (objc) {
                errCode =[NSString stringWithFormat:@"%@",[objc valueForKey:@"error_code"]];
                errMsg = [objc valueForKey:@"msg"];
                data = objc;
            }
        }
        resultBlock(requestId, errCode, errMsg, data);
    }
}

///请求失败
-(void)requestFailureForError:(NSError * _Nonnull)error andRequestId:(NSString*)requestId withResultBlock:(WBHttpPostRequestResultBlock)resultBlock{
    
    if(error && error.code == -1009){
        if(resultBlock){
            resultBlock(requestId, @"-1009",@"网络未连接，请检查后重试",nil);
        }
    }else{
        if(resultBlock){
            resultBlock(requestId, @"-2",@"网络传输异常，请检查后重试",nil);
        }
    }
}




//网络请求过程中，出现任何错误（断网，连接超时等）会进入此方法
-(void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error

{
    NSLog(@"%@",[error localizedDescription]);
}
@end
